<template>
	<el-drawer v-model="isShowDrawer" direction="rtl" :before-close="handleClose" :size="curDrawerSize" :close-on-click-modal="isReadOnly">
		<template #header="{ titleId, titleClass }">
			<div class="zs-drawer-header" :id="titleId" :class="titleClass">
				<i class="icon-b-item zs-icon zs-text-blue zs-space-right-sm"></i>
				<div class="zs-title zs-text-black">点位</div>
			</div>
		</template>

		<template #default>
			<el-container class="zs-drawer-container">
				<el-scrollbar class="zs-drawer-content">
					<!-- card1 -->
					<div class="zs-align-center zs-space-bottom" id="sm-drawer-demo-card-01">
						<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
						<div class="zs-title">点位信息</div>
					</div>
					<div class="zs-card zs-space-bottom">
						<el-form ref="form1" label-position="right" label-width="100px" :rules="rules.rules1" :model="formData.data">
							<el-form-item label="点位类型：" prop="pointType">
								<el-select v-model="formData.data.pointType" class="zs-full-item" :placeholder="isReadOnly ? ' ' : '请选择'" :disabled="handleType == 'add' ? false : true" filterable @change="clearRelevance">
									<el-option v-for="item in pointList" :key="item.id" :label="item.dicName" :value="item.id" />
								</el-select>
							</el-form-item>
							<el-form-item v-if="[1].includes(formData.data.pointType)" label="选择设备：" prop="sourceId">
								<el-select v-model="formData.data.sourceId" class="zs-full-item" :placeholder="isReadOnly ? ' ' : '请选择'" :disabled="isReadOnly" filterable @change="setEquipmentInfo">
									<el-option v-for="item in equipmentList" :key="item.id" :label="item.deviceName + '(' + item.deviceNum + ')'" :value="item.id" />
								</el-select>
							</el-form-item>
							<el-form-item v-if="[2].includes(formData.data.pointType)" label="选择设施：" prop="sourceId">
								<el-select v-model="formData.data.sourceId" class="zs-full-item" :placeholder="isReadOnly ? ' ' : '请选择'" :disabled="isReadOnly" filterable @change="setEquipmentInfo">
									<el-option v-for="item in facilityList" :key="item.id" :label="item.facilityName + '(' + item.facilityNum + ')'" :value="item.id" />
								</el-select>
							</el-form-item>
							<el-form-item v-if="[1, 2].includes(formData.data.pointType)" label="清单名称：">
								<el-input v-model="formData.data.inventoryName" disabled />
							</el-form-item>
							<el-form-item v-if="[1, 2].includes(formData.data.pointType)" label="设备楼层：">
								<el-input v-model="formData.data.floorNum" disabled />
							</el-form-item>
							<el-form-item v-if="[1, 2].includes(formData.data.pointType)" label="设备位置：">
								<el-input v-model="formData.data.deviceLocation" disabled />
							</el-form-item>
						</el-form>
					</div>
					<!-- card2 -->
					<div class="zs-align-center zs-space-top-lg zs-space-bottom" id="sm-drawer-demo-card-02">
						<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
						<div class="zs-title">点位信息</div>
					</div>
					<div class="zs-card zs-space-bottom">
						<el-form ref="form2" label-position="right" label-width="100px" :rules="rules.rules2" :model="formData.data">
							<el-form-item label="点位编号：" prop="pointNum">
								<el-input v-model="formData.data.pointNum" :maxlength="50" :disabled="handleType == 'add' ? false : true" />
							</el-form-item>
							<el-form-item label="点位名称：" prop="pointName">
								<el-input v-model="formData.data.pointName" maxlength="50" :disabled="isReadOnly" />
							</el-form-item>
							<el-form-item label="点位楼层：" prop="pointFloorNum">
								<el-select v-model="formData.data.pointFloorNum" class="zs-full-item" :placeholder="isReadOnly ? ' ' : '请选择'" :disabled="isReadOnly" filterable>
									<el-option v-for="item in dictObj.BUILDING_LEVEL" :key="item.id" :label="item.dictLabel" :value="item.dictValue" />
								</el-select>
							</el-form-item>
							<el-form-item label="点位位置：" prop="pointLocation">
								<el-input v-model="formData.data.pointLocation" :maxlength="curTextareaLength" show-word-limit type="textarea" :autosize="{ minRows: 2 }" :disabled="isReadOnly" />
							</el-form-item>
							<el-form-item label="说明：">
								<el-input v-model="formData.data.remark" :maxlength="curTextareaLength" show-word-limit type="textarea" :autosize="{ minRows: 2 }" :disabled="isReadOnly" />
							</el-form-item>
						</el-form>
					</div>
					<!-- card3 -->
					<EffectAndFailureTime ref="effectTimeRef" title="生效状态" id="sm-drawer-demo-card-03" :isReadOnly="isReadOnly" labelWidth="110px" />
					<!-- card4 -->
					<CreateUserInfo v-if="formData.data.id" ref="createDataRef" title="创建信息" id="create-user-info" />
				</el-scrollbar>
				<hsDocWrapper :nodeList="curNodeList" />
			</el-container>
		</template>

		<template v-if="handleType != 'info'" #footer>
			<div>
				<el-button class="zs-btn-md zs-btn-primary" @click="doConfirm">提交</el-button>
			</div>
		</template>
	</el-drawer>
</template>

<script setup>
	import EffectAndFailureTime from '@/components/effectAndFailureTime.vue';
	import CreateUserInfo from '@/components/createUserInfo.vue';
	import { inspectAddApi, inspectUpdateApi, inspectInfoApi } from '@/api/inspect.js';
	import { equipmentListApi } from '@/api/equipment.js';
	import { facilityListApi } from '@/api/facility.js';
	import { ElMessage } from 'element-plus';
	import { ref, reactive, watch, nextTick } from 'vue';
	import { useStore } from 'vuex';
	import { useRoute } from 'vue-router';

	const route = useRoute();

	const props = defineProps({
		isShow: { type: Boolean, default: false },
		isReadOnly: { type: Boolean, default: true },
		handleType: { type: String, default: '' },
		currentRow: { type: Object },
		pointList: { type: Array },
	});

	let store = useStore();
	const curDrawerSize = ref(store.state.uiDrawerSize);
	const curTextareaLength = ref(store.state.uiTextareaLength);

	let dictObj = store.getters.getDictObj(['VALIDATE_FLAG', 'BUILDING_LEVEL']);

	const emit = defineEmits(['close']);

	let isShowDrawer = ref(props.isShow);

	let formData = reactive({ data: {} });

	const rules = reactive({
		rules1: {
			pointType: [{ required: true, message: '请选择点位类型', trigger: ['blur', 'change'] }],
			sourceId: [{ required: true, message: '请选择设备设施', trigger: ['blur', 'change'] }],
		},
		rules2: {
			pointNum: [
				{ required: true, message: '请填写点位编号', trigger: ['blur', 'change'] },
				{ pattern: /^[a-zA-Z0-9_-]+$/, message: '输入支持大小写字母，数字，下划线，中横线' },
			],
			pointName: [{ required: true, message: '请填写点位名称', trigger: 'blur' }],
			pointFloorNum: [{ required: true, message: '请选择点位楼层', trigger: ['blur', 'change'] }],
			pointLocation: [{ required: true, message: '请填写点位位置', trigger: 'blur' }],
		},
	});

	const curNodeList = ref([
		{ name: '点位信息', id: 'sm-drawer-demo-card-01' },
		{ name: '点位信息', id: 'sm-drawer-demo-card-02' },
		{ name: '生效状态', id: 'sm-drawer-demo-card-03' },
	]);

	const form1 = ref();
	const form2 = ref();
	const forms = [form1, form2];
	const effectTimeRef = ref();
	const createDataRef = ref();

	watch(
		() => props.isShow,
		(newVal, oldVal) => {
			isShowDrawer.value = newVal;
			nextTick(() => {
				newVal && props.handleType == 'add' && initForm();
				newVal && ['info', 'edit'].includes(props.handleType) && getInfo(props.currentRow?.id);
			});
		},
	);

	//详情
	const getInfo = async id => {
		let res = await inspectInfoApi(id);
		if (res.data.code !== 200) return;
		let existCreate = curNodeList.value.find(item => item.id === 'create-user-info');
		!existCreate && curNodeList.value.push({ name: '创建信息', id: 'create-user-info' });
		formData.data = Object.assign(res.data.data);
		formData.data.sourceId != "3" && setEquipmentInfo(formData.data.sourceId);
		effectTimeRef.value.setTime({ effectTime: formData.data.startTime, expireTime: formData.data.endTime });
		nextTick(() => {
			createDataRef.value.setData(formData.data);
		});
	};

	//提交
	const doConfirm = async () => {
		const validatePromises = forms.map(form => new Promise(resolve => form.value.validate(resolve)));
		const timeModel = effectTimeRef.value.checkRequired();
		validatePromises.push(timeModel);

		Promise.all(validatePromises).then(async results => {
			const isValid = results.every(valid => valid);
			if (!isValid) return;
			let params = Object.assign(formData.data, effectTimeRef.value.getFiled());
			formData.data.projectCode = route.query.projectCode;
			let res = formData.data.id ? await inspectUpdateApi(params) : await inspectAddApi(params);
			if (res.data.code == 200) {
				ElMessage({
					message: '提交成功',
					type: 'success',
				});
				isShowDrawer.value = false;
				emit('close', { isShow: false, isRefresh: true });
			}
		});
	};

	//关闭抽屉
	const handleClose = done => {
		effectTimeRef.value.restTime();
		emit('close', { isShow: false });
		done();
	};

	//表单初始化
	const initForm = () => {
		formData.data = {};
		effectTimeRef.value.setTime({});
		let existCreate = curNodeList.value.find(item => item.id === 'create-user-info');
		existCreate && curNodeList.value.pop();
		forms.forEach(form => {
			form.value.resetFields();
		});
	};

	//改变设备设施设备相关数据
	const setEquipmentInfo = id => {
		let sourceList = formData.data.pointType == 1 ? equipmentList.value : facilityList.value
		let target = sourceList.find(item => item.id == id);
		if (!target) return;
		formData.data.inventoryName = target.inventoryName;
		formData.data.floorNum = target.floorNum;
		formData.data.deviceLocation = target.location;
		if (!formData.data.id) {
			formData.data.pointFloorNum = target.floorNum;
			formData.data.pointLocation = target.location;
		}
	};

	//切换类型清空选中的和校验
	const clearRelevance = () => {
		let clearList = ["sourceId","inventoryName","floorNum","deviceLocation","pointFloorNum","pointLocation"]
		clearList.forEach(filed => {
			formData.data[filed] = ""
		})
		form1.value.clearValidate()
		form2.value.clearValidate()
	}

	// 设备数据源
	let equipmentList = ref([]);
	const getEquipmentList = async () => {
		let res = await equipmentListApi({
			projectCode: route.query.projectCode,
			auditStatus: '1',
		});
		if (res.data.code !== 200) return;
		res.data.data.list &&
			res.data.data.list.forEach(item => {
				item.location = item.deviceLocation;
			});
		equipmentList.value = res.data.data.list || [];
	};

	// 设施数据源
	let facilityList = ref([]);
	const getFacilityListList = async () => {
		let res = await facilityListApi({
			projectCode: route.query.projectCode,
			auditStatus: '1',
		});
		if (res.data.code !== 200) return;
		res.data.data.list &&
			res.data.data.list.forEach(item => {
				item.location = item.facilityLocation;
			});
		facilityList.value = res.data.data.list || [];
	};

	getEquipmentList();
	getFacilityListList();
	defineExpose({ initForm, getInfo });
</script>
